{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "932632a0",
   "metadata": {},
   "source": [
    "1. 模型部署, c++ ?\n",
    "2. 模型蒸馏？\n",
    "\n",
    "先介绍一个模型架构查看工具：[Netron](https://github.com/lutzroeder/netron), 支持查看目前主流的DL框架导出的模型文件。\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "2d278dfd",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "import torch.onnx\n",
    "import onnx\n",
    "\n",
    "\n",
    "# 定义模型\n",
    "class IrisModel(nn.Module):\n",
    "    def __init__(self, num_features, num_labels):\n",
    "        super(IrisModel, self).__init__()\n",
    "        self.fc_0 = nn.Linear(num_features, 25) \n",
    "        self.fc_1 = nn.Linear(25, 30) \n",
    "        self.fc_2 = nn.Linear(30, num_labels) \n",
    "\n",
    "    def forward(self, x):\n",
    "        out = F.relu(self.fc_0(x))\n",
    "        out = F.relu(self.fc_1(out))\n",
    "        out = self.fc_2(out)\n",
    "        return out\n",
    "\n",
    "model = IrisModel(4,3) #模型初始化,特征的维度=4，iris有3个分类\n",
    "example_inputs = torch.rand(2,4) #定义一个模型的输入数据，随机的就成\n",
    "# print(example_inputs)\n",
    "# print(example_inputs.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "6dd9bbbc",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1.使用torch.jit.trace保存模型文件\n",
    "# https://pytorch.org/tutorials/advanced/cpp_export.html\n",
    "traced_script_module = torch.jit.trace(model, example_inputs) #使用torch.jit.trace 模型\n",
    "traced_script_module.save(\"traced_script_module.pt\") #保存模型，可以使用Netron查看模型结构\n",
    "\n",
    "# 使用c++ 加载模型文件\n",
    "# 请求c++ 服务 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "4b98b723",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2.使用onnx格式保存模型文件 https://onnxruntime.ai/\n",
    "# https://pytorch.org/tutorials/advanced/super_resolution_with_onnxruntime.html\n",
    "torch.onnx.export(model,             # model being run\n",
    "           example_inputs,           # model input (or a tuple for multiple inputs)\n",
    "          \"traced_script_module.onnx\",   # where to save the model (can be a file or file-like object)\n",
    "          export_params=True,        # store the trained parameter weights inside the model file\n",
    "          opset_version=10,          # the ONNX version to export the model to\n",
    "          do_constant_folding=True,  # whether to execute constant folding for optimization\n",
    "          input_names = ['input'],   # the model's input names\n",
    "          output_names = ['output'], # the model's output names\n",
    "          dynamic_axes={'input' : {0:'batch_size', 1:\"num_features\"},    # variable length axes\n",
    "                        'output': {0:'batch_size', 1:\"num_labels\"}})\n",
    "\n",
    "onnx_model = onnx.load(\"traced_script_module.onnx\")\n",
    "onnx.checker.check_model(onnx_model)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9aff5e09",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
